import { message } from 'antd';
import axios from 'axios';
const CancelToken = axios.CancelToken;
axios.defaults.timeout = 50000;
//返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;

//HTTPrequest拦截
axios.interceptors.request.use(
  (config) => {
    message.loading({
      content: '处理中...',
      duration: 0,
      key: 'loadingInstance',
    });
    if (!config.noToken) {
      config.headers['Authorization'] = `Bearer ${localStorage.getItem(
        'token',
      )}`;
    }
    return config;
  },
  (error) => {
    message.destroy('loadingInstance');
    return Promise.reject(error);
  },
);
//HTTPresponse拦截
axios.interceptors.response.use(
  (res) => {
    message.destroy('loadingInstance');
    const status = res.status;
    const msg = res.data.msg;
    // 如果请求为非200否者默认统一处理
    if (status != 200) {
      message.destroy();
      msg && message.error(msg);
      return Promise.reject(new Error(msg));
    }
    return res.data;
  },
  (error) => {
    message.destroy('loadingInstance');
    return Promise.reject(new Error(error));
  },
);

export function get(url, param) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url,
      params: param,
      cancelToken: new CancelToken((c) => {}),
    })
      .then((res) => {
        //axios返回的是一个promise对象
        resolve(res); //resolve在promise执行器内部
      })
      .catch((err) => {
        reject(err);
        console.log(err, '异常');
      });
  });
}

//post请求
export function post(url, param, noToken) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url,
      data: param,
      cancelToken: new CancelToken((c) => {}),
      noToken,
    })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

//put请求
export function put(url, param) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'put',
      url,
      data: param,
      cancelToken: new CancelToken((c) => {}),
    })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        console.log(err, '异常');
      });
  });
}

//del请求
export function del(url, param) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'delete',
      url,
      data: param,
      cancelToken: new CancelToken((c) => {}),
    })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        console.log(err, '异常');
      });
  });
}
